#!/bin/sh

#
# RedPorts Tinderbox backend maintenance script
#
# $Id: rpmaintainbuild 645 2014-12-05 14:23:37Z mathieu.arnold@gmail.com $
#

POUDRIERE=/poudriere
ZFSROOT=zroot

UPDATEJAIL=no
CLEANPACKAGES=no
CLEANTEMP=no
CLEANJAILREMOVE=no

while getopts dlpqrtux arg >/dev/null 2>&1
do
    case "${arg}" in
        p)   CLEANPACKAGES=yes ;;
        r)   CLEANTEMP=yes ;;
        u)   UPDATEJAIL=yes
             CLEANTEMP=yes
             CLEANPACKAGES=yes ;;
        x)   CLEANPACKAGES=yes
             CLEANTEMP=yes
             CLEANJAILREMOVE=yes ;;
        [?]) echo "Unknown option -${OPTARG}" exit 1 ;;
    esac
done
shift `expr $OPTIND - 1`

if [ -z "$1" ]; then
    echo "Usage ${0##*/} [dlprtux] build"
    echo ""
    echo "Options:"
    echo "  -r          Recovery after a crash"
    echo "  -u          Update tinderbox jail and cleanup what is required"
    echo "  -x          Remove build completely"
    echo ""
    echo "Expert Options:"
    echo "  -p          Remove all packages for build"
    echo ""
    exit 1
fi

BUILD=$1

if [ "${CLEANTEMP}" = "yes" ]; then
    echo "Cleaning up the ports tree"
    zfs rollback ${ZFSROOT}${POUDRIERE}/ports/${BUILD}@clean
    echo "Cleaning up the build"
    /usr/local/bin/poudriere jail -j ${BUILD} -p ${BUILD} -k
fi

if [ "${UPDATEJAIL}" = "yes" ]; then
    echo "Updating jail ${BUILD}"
    /usr/local/bin/poudriere jail -u -j ${BUILD}

    if [ -f "${POUDRIERE}/jails/${BUILD}/.svnrev.txt" ]
    then
      tmp=`mktemp -u`
      echo `cat /usr/local/etc/poudriere.d/jails/${BUILD}/version`@`cat ${POUDRIERE}/jails/${BUILD}/.svnrev.txt`> $tmp
      mv $tmp /usr/local/etc/poudriere.d/jails/${BUILD}/version
    fi
fi

if [ "${CLEANPACKAGES}" = "yes" ]; then
    echo "Removing all packages for build ${BUILD}"
    rm -rf ${POUDRIERE}/data/packages/${BUILD}-${BUILD}
fi

if [ "${CLEANJAILREMOVE}" = "yes" ]; then
    echo "Removing jail ${BUILD}"
    /usr/local/bin/poudriere jail -j ${BUILD} -d
    echo "Removing portstree for ${BUILD}"
    /usr/local/bin/poudriere ports -p ${BUILD} -d
fi

echo "Successfully Finished!"

exit 0
